<?php



namespace App\Model;

use Illuminate\Database\Eloquent\Model;

/**
 * 聊天记录
 */
class UserMsgLog extends Model
{
    protected $table = 'user_msg_log';
    protected $fillable = [
        'msg_type', 'from_userid', 'to_userid', 'from_account', 'to_account', 'msg_detail', 'flag'
    ];

    const RONG_TEXT_TYPE = 'RC:TxtMsg';
    const RONG_IMG_TYPE = 'JT:USER_IMAGE';
    const RONG_SOUND_TYPE = 'RC:HQVCMsg';
    const RONG_VIDEO_TYPE = 'JT:USER_VIDEO';
    const MSG_TYPE = [
        self::RONG_TEXT_TYPE => '文字',
        self::RONG_IMG_TYPE => '图片',
        self::RONG_SOUND_TYPE => '声音',
        self::RONG_VIDEO_TYPE => '视频',
    ];


    public function fromProfile()
    {
        return $this->belongsTo(UserProfile::class, 'from_userid', 'user_id');
    }

    public function toProfile()
    {
        return $this->belongsTo(UserProfile::class, 'to_userid', 'user_id');
    }

    static function unpackDetail($msgDetail = '', $msgType = self::RONG_TEXT_TYPE)
    {
        if (is_string($msgDetail) && $msgDetail) $msgDetail = json_decode($msgDetail, true);
        switch ($msgType) {
            case self::RONG_TEXT_TYPE:
                return ['content' => $msgDetail['content']['content'] ?? ''];
            case self::RONG_SOUND_TYPE:
                return ['content' => $msgDetail['content']['remoteUrl'] ?? ''];
            case self::RONG_IMG_TYPE:
                return ['content' => $msgDetail['content']['ext_info']['thumbnail'] ?? ''];
            case self::RONG_VIDEO_TYPE:
                return ['content' => $msgDetail['content']['ext_info']['image'] ?? ''];
        }
        return ['content' => $msgDetail['content']['content'] ?? ''];
    }
}
